package com.smart.web.controller.system;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.smart.common.constant.GlobalConstants;
import com.smart.common.core.domain.AjaxResult;
import com.smart.common.core.domain.R;
import com.smart.common.core.page.PageQuery;
import com.smart.common.utils.DateUtils;
import com.smart.system.domain.*;
import com.smart.system.domain.vo.AreaScreenVo;
import com.smart.system.domain.vo.EmployeeScreenVo;
import com.smart.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/screen/data")
@Api(tags = "数据大屏接口")
public class ScreenDataController {
    @Autowired
    private IBucketCapacityRecordService bucketCapacityRecordService;

    @Autowired
    private IAreaService areaService;

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IEmployeeTrajectoryService employeeTrajectoryService;

    @Autowired
    private ICarService carService;

    @Autowired
    private IBucketService bucketService;

    @Autowired
    private IAttendanceRecordService attendanceRecordService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ICarTrajectoryService carTrajectoryService;

    @Autowired
    private IGasRecordService gasRecordService;

    @ApiOperation(value = "获取区域列表")
    @GetMapping("/listScreenArea")
    public R<IPage<AreaScreenVo>> list(PageQuery pageQuery)
    {
        return R.ok(areaService.listScreenArea(pageQuery.toPage()));
    }

    @ApiOperation(value = "获取人员列表")
    @GetMapping("/listEmployeeScreen")
    public R<IPage<EmployeeScreenVo>> listEmployeeScreen(Integer areaId, PageQuery pageQuery)
    {
        return R.ok(employeeService.listEmployeeScreen(areaId,pageQuery.toPage()));
    }

    @ApiOperation(value = "获取车辆列表")
    @GetMapping("/listCar")
    public R<IPage<Car>> listCar(Integer areaId, PageQuery pageQuery)
    {
        return R.ok(carService.listCar(areaId,pageQuery.toPage()));
    }

    @ApiOperation(value = "获取环卫站")
    @GetMapping("/listBucket")
    public R<IPage<Bucket>> listBucket(Integer areaId, PageQuery pageQuery)
    {
        return R.ok(bucketService.listBucket(areaId,pageQuery.toPage()));
    }

    @ApiOperation(value = "获取大屏统计信息")
    @GetMapping("/getScreenData")
    public R getScreenData()
    {
        HashMap<String, Object> resMap = new HashMap<>();
        List<Employee> employees = employeeService.list(Wrappers.lambdaQuery(Employee.class)
                .eq(Employee::getDelFlag, GlobalConstants.DEL_FLAG_NO)
                .eq(Employee::getStatus, GlobalConstants.SUCCESS));
        //查询每个人是否有上班卡
        List<AttendanceRecord> attendances = attendanceRecordService.list(Wrappers.lambdaQuery(AttendanceRecord.class)
                .ge(AttendanceRecord::getAttendanceDate, DateUtils.getDate())
        );
        int restingEmployees = 0;
        int workingEmployees = 0;
        for (AttendanceRecord attendance : attendances) {
            for (Employee employee : employees) {
                if (employee.getId().equals(attendance.getUserId())) {
                    if (attendance.isRest()){
                        restingEmployees++;
                        continue;
                    }
                    workingEmployees++;
                }
            }
        }
        List<Car> cars = carService.list(Wrappers.lambdaQuery(Car.class)
                .eq(Car::getDelFlag, GlobalConstants.DEL_FLAG_NO)
        );
        int restingCars = 0;
        int workingCars = 0;
        for (Car car : cars) {
            if("0".equals(car.getStatus())){
                workingCars++;
                continue;
            }
            restingCars++;
        }
        resMap.put("restingEmployees", restingEmployees);
        resMap.put("workingEmployees", workingEmployees);
        resMap.put("restingCars", restingCars);
        resMap.put("workingCars", workingCars);
        return R.ok(resMap);
    }

    @ApiOperation(value = "获取考勤监测")
    @GetMapping("/getAttendanceMonitor")
    public R getAttendanceMonitor()
    {
        List<AttendanceRecord> list = attendanceRecordService.list(Wrappers.lambdaQuery(AttendanceRecord.class).apply("attendance_date = '" + DateUtils.getDate() + "'"));
        HashMap<String, String> resMap = new HashMap<>();
        resMap.put("count", String.valueOf(list.size()));
        int x = 0;
        int y = 0;
        for (AttendanceRecord attendanceRecord : list) {
            //正常,请假
            if (GlobalConstants.ATTENDANCE_NORMAL.equals(attendanceRecord.getAttendance())||
                GlobalConstants.ATTENDANCE_LEAVE.equals(attendanceRecord.getAttendance())
            ) {
                x++;
            } else {
                y++;
            }
        }
        resMap.put("normal", String.valueOf(x));
        resMap.put("abnormal", String.valueOf(y));
        if(list==null||list.size()==0){
            resMap.put("normalPercent", String.valueOf(0));
            resMap.put("abnormalPercent", String.valueOf(0));
        }else{
            double normalPercent = ((double) x / list.size()) * 100;
            double abnormalPercent = ((double) y / list.size()) * 100;
            resMap.put("normalPercent", String.valueOf(String.format("%.2f", normalPercent)));
            resMap.put("abnormalPercent", String.valueOf(String.format("%.2f", abnormalPercent)));
        }

        return R.ok(resMap);
    }

    @ApiOperation(value = "获取环卫人员/车辆/垃圾箱/桶/站,定位信息")
    @GetMapping("/getMapData")
    public R getMapData(Integer areaId)
    {
        return R.ok(areaService.getMapData(areaId));
    }

    @ApiOperation(value = "人员轨迹")
    @GetMapping("/getMapEmployeeList")
    public List<AreaLocation> getEmployeeTrajectory(String employeeId)
    {
        //获取今天轨迹
        List<EmployeeTrajectory> list = employeeTrajectoryService.list(Wrappers.lambdaQuery(EmployeeTrajectory.class)
                .eq(EmployeeTrajectory::getUserId, employeeId)
                .apply("date_format(create_time,'%Y-%m-%d') = date_format(now(),'%Y-%m-%d')")
                .orderByDesc(EmployeeTrajectory::getCreateTime)
        );
        AtomicInteger i = new AtomicInteger();
        //将数据转换为List<AreaLiocation>
        List<AreaLocation> locations = list.stream().map(item -> {
            AreaLocation areaLocation = item.getAreaLocation();
            areaLocation.setNumber(""+(i.addAndGet(1)));
            areaLocation.setTime(item.getCreateTime());
            return areaLocation;
        }).collect(Collectors.toList());
        //抽稀
        List<AreaLocation> simplify = EnhancedTrajectorySimplifier.simplify(locations, 5, true);
        return simplify;
    }

    @ApiOperation(value = "车辆轨迹")
    @GetMapping("/getMapCarList")
    public List<AreaLocation> getCarTrajectory(String carId)
    {
        //获取今天轨迹
        List<CarTrajectory> list = carTrajectoryService.list(Wrappers.lambdaQuery(CarTrajectory.class)
                .eq(CarTrajectory::getCarId, carId)
                .apply("date_format(create_time,'%Y-%m-%d') = date_format(now(),'%Y-%m-%d')")
                .orderByDesc(CarTrajectory::getCreateTime)
        );
        AtomicInteger i = new AtomicInteger();
        //将数据转换为List<AreaLiocation>
        List<AreaLocation> locations = list.stream().map(item -> {
            AreaLocation areaLocation = item.getAreaLocation();
            areaLocation.setNumber(""+(i.addAndGet(1)));
            areaLocation.setTime(item.getCreateTime());
            return areaLocation;
        }).collect(Collectors.toList());
        return EnhancedTrajectorySimplifier.simplify(locations, 10, true);
    }

    @ApiOperation(value = "环卫站监测")
    @GetMapping("/getBucketMonitor")
    public AjaxResult getBucketMonitor()
    {
        AjaxResult res = new AjaxResult();
        res.put("code", 200);
        res.put("msg", "success");
        Map map = bucketCapacityRecordService.getBucketMonitor();
        res.put("data", map);
        return res;
    }
    public Map getMap(String value1,String value2){
        HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("output", value1);
        objectObjectHashMap.put("throughput", value2);
        return objectObjectHashMap;
    }

    @ApiOperation(value = "作业监测")
    @GetMapping("/getWorkMonitor")
    public R getWorkMonitor()
    {
        return R.ok(areaService.getWorkMonitor());
    }

    @ApiOperation(value = "获取垃圾站气体监测信息")
    @GetMapping("/getGasMonitor")
    public R getGasMonitor() {
            return R.ok(gasRecordService.getGasMonitor());
    }
}
